var express = require('express');
var router = express.Router();
var studentData = require('../data/studentData.js');

router.get('/list', function (req, res, next) {
    if (!req.query.pageIndex) {
        res.send('缺少pageIndex')
    }

    if (!req.query.pageSize) {
        res.send('缺少pageSize')
    }

    let data = studentData.filter(item => {
        return item.studentId.includes(req.query.studentId) && item.studentName.includes(req.query.studentName)
    })

    let start = (Number(req.query.pageIndex) - 1) * req.query.pageSize
    let end = Number(req.query.pageIndex) * req.query.pageSize

    res.send({
        pageIndex: req.query.pageIndex,
        pageSize: req.query.pageSize,
        total: data.length,
        data: data.slice(start, end)
    })
})

router.post('/add', function (req, res, next) {

    let data = {
        studentId: req.body.studentId,
        studentName: req.body.studentName,
        sex: req.body.sex,
        age: req.body.age,
        birthday: req.body.birthday,
        identityCard: req.body.identityCard,
        nation: req.body.nation,
        nativePlace: req.body.nativePlace
    }

    studentData.push(data)

    res.send({
        msg: '新增成功',
        code: 200,
        data: true
    })
})

router.put('/update', function (req, res, next) {
    if (!req.body.studentId) {
        res.send('缺少id字段')

        return
    }

    let index = studentData.findIndex(item => {
        return String(item.studentId) === String(req.body.studentId)
    })

    if (index < 0) {
        res.send({
            msg: '编辑失败，未通过studentId找到对应数据',
            code: 500,
            data: false
        })

        return
    }

    studentData[index] = Object.assign({}, req.body)

    res.send({
        msg: '编辑成功',
        code: 200,
        data: true
    })
})

router.delete('/delete', function (req, res, next) {
    console.log(req.query)
    if (!req.query.studentId) {
        res.send('缺少studentId字段')
    }

    let index = studentData.findIndex(item => {
        return Number(item.studentId) === Number(req.query.studentId)
    })

    if (index < 0) {
        res.send({
            msg: '删除失败，未能通过studentId找到对应数据',
            code: 500,
            data: false
        })
        return
    }

    studentData.splice(index, 1)

    res.send({
        msg: '删除成功',
        code: 200,
        data: true
    })
})

module.exports = router